package ua.kharkov.knure.pereverziev.diploma.web.command.ajax;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import ua.kharkov.knure.pereverziev.diploma.db.DAOServices.ScheduleService;
import ua.kharkov.knure.pereverziev.diploma.db.DAOServices.ServiceFactory;
import ua.kharkov.knure.pereverziev.diploma.db.entity.Airport;
import ua.kharkov.knure.pereverziev.diploma.web.command.Command;

public class AjaxTimetable implements Command {

	private static final long serialVersionUID = -688126913159229771L;
	private static final Logger log = Logger.getLogger(AjaxTimetable.class);

	@Override
	public String execute(final HttpServletRequest request,
			final HttpServletResponse response) throws IOException,
			ServletException {

		log.debug("Command starts");
		final HttpSession session = request.getSession();
		final String airportId = request.getParameter("airport");
		log.debug("airportId = " + airportId);
		final Airport airport = ServiceFactory.getInstance()
				.getAirportService().get(Long.parseLong(airportId));
		if (airport == null) {
			log.error("Cannot find airport with id=" + airportId);
		} else {
			final ScheduleService scheduleService = ServiceFactory
					.getInstance().getScheduleService();

			session.setAttribute("schedule_dep",
					scheduleService.getDeparturesSchedule(airport));

			session.setAttribute("schedule_ariv",
					scheduleService.getArrivalsSchedule(airport));
		}
		final String forward = "/WEB-INF/ajax_pages/timetable.jsp";
		log.debug("Command finished");
		return forward;
	}
}
